package com.easy.common.util;
//密码加密
import cn.hutool.crypto.digest.DigestUtil;

public class PasswordUtil {
    private final static char[] arr = {'a', 'b', 'c', 'd', 'e', 'f',  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    private final static int salt_index = 5;
    private final static int count_index = 15;
    public static String getEncryption(String  password) {
        //随机盐值
        int index_salt = (int) (Math.random() * arr.length);
        char salt = arr[index_salt];
        //随机加密次数
        int index_count = (int) (Math.random() * arr.length);
        char count = arr[index_count];
        String encryptionPassword = password+salt;
        for (int i = 0; i < count; i++) {
            encryptionPassword = DigestUtil.md5Hex(encryptionPassword);
        }
        StringBuilder strb=new StringBuilder(encryptionPassword);
        strb.insert(salt_index, salt);
        strb.insert(count_index, count);
        return strb.toString();
    }
    //验证密码是否正确
    public static boolean checkPassword(String password, String encryptionPassword) {
        //盐值
        char salt = encryptionPassword.charAt(salt_index);
        //加密次数
        char count = encryptionPassword.charAt(count_index);
        System.out.println( salt+"---"+count);
        String decode=password+salt;
        for (int i = 0; i < count; i++) {
            decode = DigestUtil.md5Hex(decode);
        }
        // 构建加密后的字符串，并将盐值和加密次数插入到固定位置
        StringBuilder strb=new StringBuilder(decode);
        strb.insert(salt_index, salt);
        strb.insert(count_index, count);
        System.out.println(strb.toString());
        // 比较生成的字符串与存储的加密字符串是否一致
        return strb.toString().equals(encryptionPassword);
    }
    //测试
    public static void main(String[] args) {
        System.out.println(getEncryption("111111"));
    }
}
